﻿using System;
using System.Collections.Generic;

namespace HBFramework
{
    public class TimerManager : Singleton<TimerManager>, ISingleton, ISingletonUpdate
    {
        private List<ITimer> timerList;

        int ISingletonUpdate.Order => 1;

        void ISingleton.OnInit()
        {
            timerList = new List<ITimer>();
        }

        void ISingletonUpdate.OnUpdate()
        {
            for (int i = 0; i < timerList.Count; i++)
            {
                if (timerList[i].IsStop)
                {
                    timerList.RemoveAt(i);
                    i--;
                    continue;
                }
                timerList[i].OnUpdate();
            }
        }

        void ISingleton.OnDestroy()
        {
            for (int i = 0; i < timerList.Count; i++)
            {
                timerList[i].OnStop();
            }
            timerList.Clear();
        }

        /// <summary>
        /// 开启计时器
        /// </summary>
        /// <param name="timer"></param>
        public void StartTimer(ITimer timer)
        {
            timer.OnStart();
            timerList.Add(timer);
        }

        /// <summary>
        /// 停止计时器
        /// </summary>
        /// <param name="timer"></param>
        public void StopTimer(ITimer timer)
        {
            timer.OnStop();
            timerList.Remove(timer);
        }

        /// <summary>
        /// 延迟执行
        /// </summary>
        /// <param name="time"></param>
        /// <param name="onFinish"></param>
        /// <returns></returns>
        public ITimer Dely(float time, Action onFinish)
        {
            var timer = new SecondTimer(time, onStop: onFinish, onFinish: onFinish);
            StartTimer(timer);
            return timer;
        }
    }
}